package org.feuyeux.opentracing;

import com.google.common.collect.ImmutableMap;
import io.dropwizard.Application;
import io.dropwizard.Configuration;
import io.dropwizard.setup.Environment;
import io.opentracing.Scope;
import io.opentracing.Span;
import io.opentracing.Tracer;
import lombok.extern.slf4j.Slf4j;
import org.feuyeux.opentracing.lib.Tracing;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.TimeUnit;

@Slf4j
public class HelloB extends Application<Configuration> {

    private final Tracer tracer;

    private HelloB(Tracer tracer) {
        this.tracer = tracer;
    }

    @Path("/")
    @Produces(MediaType.TEXT_PLAIN)
    public class PublisherResource {
        @GET
        @Path("/x")
        public String x(@Context HttpHeaders httpHeaders, @QueryParam("s") String... ss) {
            Span span = Tracing.startServerSpan(tracer, httpHeaders, "b-x");
            StringBuilder r = new StringBuilder();
            try (Scope scope = tracer.scopeManager().activate(span)) {
                for (String s : ss) {
                    log.info("s:{}", s);
                    r.append(s).append(":");
                    TimeUnit.MILLISECONDS.sleep(100);
                    span.log(ImmutableMap.of("event", "x", "value", s));
                }
            } catch (InterruptedException e) {
                log.error("", e);
            } finally {
                span.finish();
            }
            return "x(" + r.toString() + ")";
        }

        @GET
        @Path("/y")
        public String y(@Context HttpHeaders httpHeaders, @QueryParam("t") String t, @QueryParam("s") String s) {
            Span span = Tracing.startServerSpan(tracer, httpHeaders, "b-y");
            try (Scope scope = tracer.scopeManager().activate(span)) {
                log.info("t:{},s:{}", t, s);
                TimeUnit.MILLISECONDS.sleep(100);
                span.log(ImmutableMap.of("event", "y", "value", t));
            } catch (InterruptedException e) {
                log.error("", e);
            } finally {
                span.finish();
            }
            return "y(" + t + ";" + s + ")";
        }
    }

    @Override
    public void run(Configuration configuration, Environment environment) throws Exception {
        environment.jersey().register(new PublisherResource());
    }

    public static void main(String[] args) throws Exception {
        System.setProperty("dw.server.applicationConnectors[0].port", "8082");
        System.setProperty("dw.server.adminConnectors[0].port", "9082");

        new HelloB(Tracing.init("B")).run(args);
    }
}
